import axios from 'axios'
import store from '@/store'
import { router } from '@/router'
import qs from 'qs'
import { getToken } from '@/utils/auth'
import { Message } from '@cci/cui'

// create an axios instance
// const baseURL = process.env.VUE_APP_ENV === 'development' ? '/api' : process.env.VUE_APP_BASE_URL

const service = axios.create({
  baseURL: '/api',
  timeout: 30000 // request timeout
})

// 无响应拦截器 用于同步接口
export const requestNoRes = axios.create({
  baseURL: '/api',
  timeout: 0 // request timeout
});

[service, requestNoRes].forEach(item => {
  item.interceptors.request.use(
    config => {
      if (store.getters.token) {
        config.headers.accessToken = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      }
      if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded' && config.data && Object.prototype.toString.call(config.data) === '[object Object]') {
        config.data = qs.stringify(config.data)
      }
      if (config.headers['Content-Type'] === 'application/json' && config.data && (Object.prototype.toString.call(config.data) === '[object Object]' || Object.prototype.toString.call(config.data) === '[object Array]')) {
        config.data = JSON.stringify(config.data)
      }
      return config
    },
    error => {
      // do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    })
})
// request interceptor

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom success is not true, it is judged as an error.
    if (Object.prototype.toString.call(res) === '[object Object]' && !res.success) {
      if (response.config.url !== '/onm/event/type/item/export/import') { // 事项信息导入的url
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        return res
      }

      // 107 token失效
      if (res.code === 107) {
        store.dispatch('LogOut')
        // 跳转到登录页
        router.replace('/login')
      }

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      // if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      //   // to re-login
      //   MessageBox.confirm('您已经登出，您可以取消登出以留在此页面，或再次登录', '确认注销', {
      //     confirmButtonText: '重新登录',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     store.dispatch('user/resetToken').then(() => {
      //       location.reload()
      //     })
      //   })
      // }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // 用于文件流下载
      if (response.headers['content-disposition']) {
        return response
      }
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.response?.data?.message || error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
